package com.leather.admin.controller;

import com.leather.admin.service.AdminService;
import com.leather.admin.vo.AdminVo;
import com.leather.common.result.Result;
import com.leather.common.toolkits.EncryptKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }


    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {

        if (null != httpSession.getAttribute("admin")) {
            httpSession.removeAttribute("admin");
        }
        return "redirect:login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result postLogin(AdminVo adminVo, HttpSession httpSession) {
        UsernamePasswordToken token = new UsernamePasswordToken(adminVo.getAdminName(), EncryptKit.MD5(adminVo.getPassword()).toCharArray(), null);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            httpSession.setAttribute("admin", adminVo);
            return Result.success("success");
        } catch (AuthenticationException e) {
            return Result.exception(900001, e.getMessage());
        }

    }


}
